package com.github.novicezk.midjourney.service.task;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.ListUtil;
import com.github.novicezk.midjourney.ProxyProperties;
import com.github.novicezk.midjourney.ProxyProperties.DiscordConfig;
import com.github.novicezk.midjourney.service.TaskService;
import com.github.novicezk.midjourney.support.Task;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.util.List;
import java.util.Random;

public class InMemoryTaskServiceImpl implements TaskService {
	private final TimedCache<String, Task> taskMap;
	private final TimedCache<String, ProxyProperties.DiscordConfig> discordMap;

	@Autowired
	private ProxyProperties proxyProperties;

	public InMemoryTaskServiceImpl(Duration timeout, List<DiscordConfig> discords) {
		this.taskMap = CacheUtil.newTimedCache(timeout.toMillis());
		this.discordMap = CacheUtil.newTimedCache(timeout.toMillis());
	}

	@Override
	public void putTask(String key, Task task) {
		this.taskMap.put(key, task);
	}

	@Override
	public void removeTask(String key) {
		this.taskMap.remove(key);
	}

	@Override
	public Task getTask(String key) {
		return this.taskMap.get(key);
	}

	@Override
	public List<Task> listTask() {
		return ListUtil.toList(this.taskMap.iterator());
	}

//	@Override
//	public void putDiscord(String key) {
//		if (discordMap.containsKey(key)){
//			return;
//		}
//
//		int size = proxyProperties.getDiscords().size();
//		Random random = new Random(8);
//		int index = random.nextInt(size);
//		this.discordMap.put(key, proxyProperties.getDiscords().get(index));
//	}

	@Override
	public void putDiscord(String key) {
		if (!discordMap.containsKey(key)){
			List<DiscordConfig> discords = proxyProperties.getDiscords();
			if (discords.isEmpty()) {
				throw new RuntimeException("Discord列表为空");
			}
			int size = discords.size();
			Random random = new Random();
			int index = random.nextInt(size);
			this.discordMap.put(key, discords.get(index));
		}
	}

	@Override
	public void putDiscord(String key, DiscordConfig discordConfig) {
		this.discordMap.put(key, discordConfig);
	}

	@Override
	public DiscordConfig getDiscord(String id) {
		return this.discordMap.get(id);
	}


}
